package com.xyyl.patient.service.order;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xyyl.patient.core.constant.AppEnum;
import com.xyyl.patient.core.util.DateUtils;
import com.xyyl.patient.entity.archives.Archives;
import com.xyyl.patient.entity.archives.ArchivesSnapshot;
import com.xyyl.patient.entity.order.ConsultOrder;
import com.xyyl.patient.entity.user.AccountRecord;
import com.xyyl.patient.entity.user.User;
import com.xyyl.patient.mapper.archives.ArchivesMapper;
import com.xyyl.patient.mapper.archives.ArchivesSnapshotMapper;
import com.xyyl.patient.mapper.order.ConsultOrderMapper;
import com.xyyl.patient.mapper.user.AccountRecordMapper;
import com.xyyl.patient.mapper.user.UserMapper;

/**
 * @projectName:xyyl-patient-service
 * @ClassName: PhoneOrderServiceImp
 * @Description:咨询订单支付业务实现
 * @author chen
 * @date 2017年8月24日
 *
 */
@Service("consultOrderService")
public class ConsultOrderServiceImpl implements ConsultOrderService {

	@Autowired
	private ConsultOrderMapper consultOrderMapper;

	@Autowired
	private AccountRecordMapper accountRecordMapper;

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private ArchivesMapper archivesMapper;

	@Autowired
	private ArchivesSnapshotMapper archivesSnapshotMapper;

	@Override
	public int insertConsultOrder(ConsultOrder consultOrder) {

		Integer archivesSnapshotId = null;
		if (consultOrder.getArchivesid() != null) {
			archivesSnapshotId = createArchivesSnapshot(consultOrder.getArchivesid());// 档案快照ID
			consultOrder.setSnapshotid(archivesSnapshotId);
		}
		String preCode = DateUtils.formatDatetime(new Date(), "yyyyMMddHHss") + RandomUtils.nextInt(99999);
		consultOrder.setOrdersn("TO-" + preCode);
		consultOrder.setCreatetime(DateUtils.currentDatetime());
		consultOrderMapper.insert(consultOrder);

		return consultOrder.getId();
	}

	/**
	 * @Title: createArchivesSnapshot 
	 * @Description: 创建档案快照 
	 * @param @return参数 
	 * @return int 返回类型 
	 * @throws
	 */
	public int createArchivesSnapshot(Integer archiveId) {

		/** 获取原档案信息 **/
		Archives archives = archivesMapper.selectOne(archiveId);
		ArchivesSnapshot archivesSnapshot = null;
		if (archives != null) {
			archivesSnapshot = new ArchivesSnapshot();
			BeanUtils.copyProperties(archives, archivesSnapshot);
			archivesSnapshot.setId(null);
			archivesSnapshotMapper.insert(archivesSnapshot);
		}

		return archivesSnapshot.getId();
	}

	@Override
	public int updateConsultOrder(ConsultOrder consultOrder) {

		Integer payType = consultOrder.getPaytype();

		/** 1. 查询用户的账户信息 **/
		User user = userMapper.queryUserByOption(null, consultOrder.getOpenid());
		BigDecimal beforeBalance = user.getAccountbalance() == null ? new BigDecimal("0.00") : user.getAccountbalance();
		BigDecimal afterBalace = beforeBalance;

		BigDecimal payAmount = consultOrder.getPayamount(); /** 订单总金额 **/
		BigDecimal balancePayAmount = new BigDecimal("0.00");/** 账户支付金额 **/
		if (payType.equals(AppEnum.common.Order_payType_account.getValue())) {
			balancePayAmount = payAmount;
		} else if (payAmount.compareTo(afterBalace) > 0) {
			balancePayAmount = beforeBalance; /** 若微信支付，且订单金额大于账户余额，则优先扣除所有的账户余额 **/
		}
		consultOrder.setBalanceAmount(balancePayAmount);
		consultOrder.setUpdatetime(DateUtils.currentDatetime());
		consultOrder.setPaytime(DateUtils.currentDatetime());
		consultOrder.setStatus(AppEnum.common.Pay_status_confirm.getValue());
		/** 2.更新订单信息 **/
		int result = consultOrderMapper.update(consultOrder);

		/** 3.如果账户余额发生变化，则更新用户账户余额，同时新增流水 **/
		if (balancePayAmount.doubleValue() > 0.00) {
			afterBalace = afterBalace.subtract(balancePayAmount);
			user.setAccountbalance(afterBalace);
			userMapper.update(user);

			/** 4.余额支付，记录流水信息 **/
			AccountRecord accountRecord = new AccountRecord();
			accountRecord.setAmount(balancePayAmount);
			accountRecord.setOrdersn(consultOrder.getOrdersn());
			accountRecord.setChangetype(AppEnum.common.Order_changetype_out.getValue());
			accountRecord.setConsumetype(AppEnum.common.Order_consumetype_word.getValue());
			accountRecord.setPatientid(user.getId());
			accountRecord.setIncometype(0);
			accountRecord.setTotalamountBefore(beforeBalance);
			accountRecord.setTotalamountAfter(afterBalace);
			accountRecord.setCreatetime(DateUtils.currentDatetime());
			accountRecordMapper.insert(accountRecord);
		}
		return result;
	}

	@Override
	public ConsultOrder queryOrderDetailById(Integer id) {
		return consultOrderMapper.selectOne(id);
	}

	@Override
	public ConsultOrder queryOrderDetailBySn(String openid, String ordersn) {
		return consultOrderMapper.queryOrderDetailBySn(openid, ordersn);
	}

	@Override
	public ConsultOrder queryUnfinishedOrderByUid(Integer userid, Integer doctorid) {
		return consultOrderMapper.queryUnfinishedOrderByUid(userid, doctorid);
	}

	@Override
	public int confirmFinishOrder(ConsultOrder consultOrder) {
		return consultOrderMapper.updateOrderStatus(consultOrder.getId(),consultOrder.getStatus(), consultOrder.getUpdatetime(), consultOrder.getOrderType());
	}

	@Override
	public Map<String, String> queryLastArchivesInfoByUserid(Integer userid, Integer type) {
		return consultOrderMapper.queryLastArchivesInfoByUserid(userid, type);
	}

}
